﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace WebApp.ViewModels
{
    public class BaseOptions<T> where T : new()
    {
        /// <summary>
        /// 复制对象
        /// </summary>
        /// <returns></returns>
        public T Clone()
        {
            T obj = new T();

            PropertyInfo[] propsfrom = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | BindingFlags.DeclaredOnly);
            foreach (PropertyInfo fromp in propsfrom)
            {
                string fName = fromp.Name.ToUpper();

                if (fromp.CanWrite)
                {
                    fromp.SetValue(obj, fromp.GetValue(this, null), null);
                }
            }

            return obj;
        }

        public string ToJsonString()
        {
            Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings();
            settings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Include;

            return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.None, settings);
        }

        public static T Create(string json)
        {
            try
            {
                if (string.IsNullOrEmpty(json))
                {
                    return new T();
                }

                T item = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
                if (item == null)
                {
                    return new T();
                }
                else
                {
                    return item;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static IList<T> CreateList(string json)
        {
            try
            {
                if (string.IsNullOrEmpty(json))
                {
                    return new List<T>();
                }

                IList<T> item = Newtonsoft.Json.JsonConvert.DeserializeObject<IList<T>>(json);
                if (item == null)
                {
                    return new List<T>();
                }
                else
                {
                    return item;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

    }
}
